// WebGL detection and utilities

export const detectWebGL = () => {
  try {
    const canvas = document.createElement('canvas');
    const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
    
    if (!gl) {
      return {
        supported: false,
        error: 'WebGL is not supported by your browser'
      };
    }

    // Check for required extensions
    const requiredExtensions = [
      'OES_element_index_uint',
      'WEBGL_depth_texture'
    ];

    const missingExtensions = [];
    requiredExtensions.forEach(ext => {
      if (!gl.getExtension(ext)) {
        missingExtensions.push(ext);
      }
    });

    // Get WebGL info
    const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
    const vendor = debugInfo ? gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) : 'Unknown';
    const renderer = debugInfo ? gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) : 'Unknown';

    return {
      supported: true,
      version: gl.getParameter(gl.VERSION),
      vendor,
      renderer,
      maxTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE),
      maxVertexAttribs: gl.getParameter(gl.MAX_VERTEX_ATTRIBS),
      maxFragmentUniforms: gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS),
      missingExtensions
    };
  } catch (error) {
    return {
      supported: false,
      error: `WebGL detection failed: ${error.message}`
    };
  }
};

export const getWebGLErrorMessage = (webglInfo) => {
  if (webglInfo.supported) return null;

  return {
    title: 'WebGL Not Supported',
    message: webglInfo.error,
    suggestions: [
      'Update your browser to the latest version',
      'Enable hardware acceleration in your browser settings',
      'Update your graphics drivers',
      'Try using a different browser (Chrome, Firefox, Edge)',
      'Check if your device supports WebGL at webglreport.com'
    ]
  };
};

export const logWebGLInfo = (webglInfo) => {
  if (webglInfo.supported) {
    console.log('🎮 WebGL Information:');
    console.log(`  Version: ${webglInfo.version}`);
    console.log(`  Vendor: ${webglInfo.vendor}`);
    console.log(`  Renderer: ${webglInfo.renderer}`);
    console.log(`  Max Texture Size: ${webglInfo.maxTextureSize}`);
    console.log(`  Max Vertex Attributes: ${webglInfo.maxVertexAttribs}`);
    console.log(`  Max Fragment Uniforms: ${webglInfo.maxFragmentUniforms}`);
    
    if (webglInfo.missingExtensions.length > 0) {
      console.warn('⚠️ Missing WebGL Extensions:', webglInfo.missingExtensions);
    }
  } else {
    console.error('❌ WebGL Error:', webglInfo.error);
  }
};
